package com.wisewin.pose.util;

import java.security.MessageDigest;

/**
 * MD5加密工具类
 *
 * @author jason
 *
 */
public class MD5Util {

    static MessageDigest md;
    static {
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (Exception ex) {
        }
    }

    /**
     * 加密方法
     *
     * @param msg
     * @return
     */
    public static String digest(String msg) {
        byte[] rlt = md.digest(msg.getBytes());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rlt.length; i++) {
            String d = "00" + Integer.toHexString(rlt[i]);
            sb.append(d.substring(d.length() - 2));
        }
        return sb.toString();
    }

    public static String digestNew(String message) {
        String md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5"); // 创建一个md5算法对象
            byte[] messageByte = message.getBytes("UTF-8");
            byte[] md5Byte = md.digest(messageByte); // 获得MD5字节数组,16*8=128位
            md5 = bytesToHex(md5Byte); // 转换为16进制字符串
        } catch (Exception e) {
            System.out.println("erro md5 creat!!!!");
            e.printStackTrace();
        }
        return md5;
    }

    // 二进制转十六进制
    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexStr = new StringBuffer();
        int num;
        for (int i = 0; i < bytes.length; i++) {
            num = bytes[i];
            if (num < 0) {
                num += 256;
            }
            if (num < 16) {
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString();
    }

    public static void main(String[] args) {
        System.out.println(digest("admin@2025"));
        System.out.println(digestNew("9748fbea53e645cfa214b1d59a78c341264050mirror"));
    }

    // public static void main(String[] args) {
    // System.out.println(digest("666666"));
    // }
}
